/*
 * @Descripttion:
 * @Version:
 * @Author: 王传宝
 * @Date: 2023-02-27 14:43:33
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2023-03-04 09:47:02
 */
import React, { useEffect, useState } from "react";
import Style from "./DetailView.module.scss";
import {
  NavBar,
  Space,
  Swiper,
  Toast,
  Popup,
  Button,
  Selector,
  Stepper,
} from "antd-mobile";
import {
  SearchOutline,
  ReceivePaymentOutline,
  FaceRecognitionOutline,
  UnorderedListOutline,
} from "antd-mobile-icons";
import { useDispatch } from "react-redux";
import { hideTabbar } from "@/store/slices/commonSlice";
import { productDetails } from "@/api/detail";
import { List } from "antd-mobile";
import { useNavigate, useParams } from "react-router-dom";
import { changeList } from "@/store/slices/shoppingCar";

// type Props = {};
// //定义价格数据类型
// type priceType = {
//   basicPrice: string;
//   finalPrice: {
//     prefix: string;
//     price: string;
//   };
//   counterPrice: string;
// };
// //定义请求数据类型
// type DetailDateType = {
//   name: string;
//   recommendReason: Array<string>;
//   itemDiscountDetail: {
//     spmcFinalPriceDesc: string;
//   };
//   shoppingReward: {
//     name: string;
//     rewardDesc: string;
//     rewardValue: string;
//   };
//   goodCmtRate: string;
//   skuFreight: {
//     freightInfo: string;
//     policyList: [title: string, content: string];
//     title: string;
//   };
//   commentCount: number;
//   attrList: Array<{}>;
//   adBanners: [];
//   promotionDesc: string;
// };
// type itemDetailType = {
//   detailHtml: string;
// };
// //品牌名字类型
// type PNType = {
//   title: string;
//   logoUrl: string;
// };
// type yfType = {
//   title: string;
//   type: number;
//   policyList: [title: string, content: string];
//   freightInfo: string;
// };
// type gwfType = {
//   title: string;
//   ruleList: [];
// };
// type gwfruleType = [title: string, content: string];
// type brandInfoType = {
//   title: string;
//   picUrl: string;
//   desc: string;
// };

const DetailView = () => {
  //获取路由跳转函数
  const navigate = useNavigate();
  //顶部导航栏
  //获取dispatch方法
  var dispatch = useDispatch();
  const back = () =>
    Toast.show({
      content: "点击了返回区域",
      duration: 1000,
    });
  const right = (
    <div style={{ fontSize: 24 }}>
      <Space style={{ "--gap": "16px" }}>
        <SearchOutline />
        <ReceivePaymentOutline />
      </Space>
    </div>
  );
  //
  let params = useParams();
  console.log(params);

  //定义商品id,等待id参数
  const [proid, setProid] = useState(params.id);
  // let { proid } = useParams();
  // console.log(proid);
  //获取轮播图数据
  const [bannnerdata, setBannerData] = useState<any>({});

  //获取价格
  const [price, setPrice] = useState<any>();
  console.log(price?.basicPrice);
  //获取商品品牌
  const [productName, setPN] = useState<any>({});
  //获取邮费
  const [youfei, setyoufei] = useState<any>({});
  const [yfrule, setyfrule] = useState<any>([]);
  // const yfarr: any = Object.entries(youfei);
  console.log(yfrule);
  //定义购物饭
  const [gwf, setgwf] = useState<any>({});
  const [gwfrule, setgwfrule] = useState<any>([]);
  console.log(gwfrule);
  //定义弹出层
  const [visible1, setVisible1] = useState(false);
  const [visible2, setVisible2] = useState(false);
  const [visible3, setVisible3] = useState(false);
  //定义网易严选
  const [brandInfo, setbrandInfo] = useState<any>({});
  //定义商品颜色
  const [color, setcolor] = useState([]);
  console.log(color);

  //讲轮播图数据转成数组并筛选
  const newarr = Object.entries(bannnerdata)
    .splice(1, Object.entries(bannnerdata).length - 2)
    .map((val) => val[1]);
  // console.log(Object.entries(bannnerdata));
  console.log(newarr);
  //定义购物车选择状态
  console.log(color.map((val: any) => val.skuSpecValueList).flat());
  const colorcar = color
    .map((val: any) => val.skuSpecValueList)
    .flat()
    .filter((i) => i.picUrl);
  const sizecar = color
    .map((val: any) => val.skuSpecValueList)
    .flat()
    .filter((i) => i.picUrl == "");
  // const typecarr = color
  //   .map((val: any) => val.skuSpecValueList)
  //   .flat()
  //   .filter((i) => i.skuSpecId == 3906112);
  console.log(
    colorcar.filter((val) => val.id == 1124194).map((val) => val.picUrl)
  );
  const [colorid, setcolorid] = useState();
  const [sizeid, setsizeid] = useState();
  console.log(sizeid);
  // console.log(
  //   colorcar.filter((val) => val.id == colorid).map((val) => val.value)
  // );
  //定义购物车选项
  const option1 = colorcar.map((item) => ({
    ...item,
    label: item.value,
    value: item.id,
  }));
  const option2 = sizecar.map((item) => ({
    ...item,
    label: item.value,
    value: item.id,
  }));
  // const option3 = typecarr.map((item) => ({
  //   ...item,
  //   label: item.value,
  //   value: item.id,
  // }));
  console.log(option1.filter((val) => val.id == colorid));
  const [closearr, setclosearr] = useState();

  // option1.filter((val) => val.id == colorid)
  // setclosearr()
  //接收请求数据
  const [detaildata, setDetailDate] = useState<any>({});
  const [a, seta] = useState(false);
  //购物车数据
  const [num, setnum] = useState<number>(1)
  const [type, settype] = useState()
  // settype()
  
  //定义商品参数
  const [attrList, setattrList] = useState([]);
  //获取小轮播
  const [smalllunbo, setsmalllunbo] = useState([]);
  const q = smalllunbo.map((val: any) => val.picUrl);
  console.log(q);
  //加入购物车的数据
  const [cardate, setcardate] = useState();
  let data = option1.filter((val) => val.id == colorid)

  data.map(val => val.name = detaildata.name

  )
  data.map(val => val.num = num

  )
  data.map(val => val.price = price?.basicPrice - 0

  )
  // price?.basicPrice
  console.log(data);
  //发送请求,请求数据
  useEffect(() => {
    productDetails(proid as any).then((res) => {
      console.log(res);
      setBannerData(res.data.item.itemDetail);
      setPrice(res.data.item.price);
      setDetailDate(res.data.item);
      setPN(res.data.item.simpleBrandInfo);
      seta(true);
      setyoufei(res.data.item.skuFreight);
      setyfrule(res.data.item.skuFreight.policyList);
      setgwf(res.data.item.shoppingRewardRule);
      setbrandInfo(res.data.item.brandInfo);
      setattrList(res.data.item.attrList);
      setsmalllunbo(res.data.item.adBanners);
      setcolor(res.data.item.skuSpecList);

      setgwfrule(res.data.item.shoppingRewardRule.ruleList);
    });

    //去掉导航栏
    dispatch(hideTabbar());
  }, []);
  // 轮播图
  const items = newarr.map((item: any, index) => (
    <Swiper.Item key={index}>
      <img src={item} />
    </Swiper.Item>
  ));
  const items2 = q.map((item, index) => (
    <Swiper.Item key={index}>
      <img src={item} />
    </Swiper.Item>
  ));
  return (
    <div className={Style.wrap}>
      <div className={Style.nav}>
        <NavBar right={right} onBack={back}>
          网易严选
        </NavBar>
      </div>
      <div className={Style.main}>
        <div className={Style.banner}>
          <Swiper loop autoplay autoplayInterval={5000}>
            {items}
          </Swiper>
        </div>
        <div className={Style.price}>
          <span className={Style.price1}>${price?.basicPrice}</span>

          <span className={Style.handPrice}>
            <span className={Style.handPrice1}>
              {price?.finalPrice?.prefix}
            </span>
            ${price?.finalPrice?.price || price?.counterPrice}
          </span>
        </div>
        <div className={Style.detailInfo}>
          <div className={Style.protitle}>
            <span className={Style.proname}>{detaildata.name}</span>
            <span className={Style.prohow}>
              <span style={{ color: "red", fontWeight: "bold" }}>
                {detaildata.goodCmtRate}
              </span>{" "}
              好评率
            </span>
          </div>
          <p>
            <img src={productName.logoUrl} />
            {productName.title}
          </p>
          <ol className={Style.why}>
            {a &&
              detaildata.recommendReason.map((val: any, index: number) => (
                <li key={index}>{val}</li>
              ))}
          </ol>
        </div>
        <div className={Style.baoyou}>
          <List.Item
            onClick={() => {
              setVisible1(true);
            }}
            style={{ paddingLeft: 10 }}
          >
            {youfei.title}:{youfei.freightInfo}
          </List.Item>
          <Popup
            visible={visible1}
            onMaskClick={() => {
              setVisible1(false);
            }}
            bodyStyle={{ height: "40vh" }}
          >
            {
              <div className={Style.yfmain}>
                <div className={Style.title}>{youfei.title}</div>
                <div className={Style.body}>
                  <li>{youfei.freightInfo}</li>
                  <div>{yfrule[0]?.content}</div>
                </div>
              </div>
            }
          </Popup>
          {detaildata.shoppingReward && (
            <List.Item
              onClick={() => {
                setVisible2(true);
              }}
              style={{ paddingLeft: 10 }}
            >
              {detaildata.shoppingReward.name}:
              {detaildata.shoppingReward.rewardDesc}
              <span style={{ color: "red" }}>
                {detaildata.shoppingReward.rewardValue}
              </span>
            </List.Item>
          )}
          <Popup
            visible={visible2}
            onMaskClick={() => {
              setVisible2(false);
            }}
            bodyStyle={{ height: "40vh" }}
          >
            {
              <div className={Style.gwfmain}>
                {gwf && <div className={Style.title}>{gwf.title}</div>}
                <div
                  className={Style.body}
                  style={{
                    height: "40vh",
                    overflowY: "auto",
                    padding: "20px",
                  }}
                >
                  {gwfrule.map((item: any, index: number) => {
                    return <p key={index}>{item.title}</p>;
                  })}
                </div>
              </div>
            }
          </Popup>
        </div>
        <div onClick={() => { }} className={Style.pingjia}>
          <p>用户评价（{detaildata.commentCount}）</p>
          <p>
            {detaildata.goodCmtRate}好评率{">"}
          </p>
        </div>
        {detaildata && (
          <div className={Style.wyys}>
            <div className={Style.left}>
              <img src={brandInfo.picUrl} />
            </div>
            <div className={Style.right}>
              <h3>{brandInfo.title}</h3>
              <p>{brandInfo.desc}</p>
            </div>
          </div>
        )}
        <div className={Style.smalllb}>
          <Swiper autoplay loop autoplayInterval={5000}>
            {items2}
          </Swiper>
        </div>
        <div className={Style.prodetail}>
          <div className={Style.canshu}>商品参数</div>
          <div>
            {attrList.map((item: any, index: number) => {
              return (
                <p key={index}>
                  <span>{item.attrName} : </span>
                  <span className={Style.canshuinfo}>{item.attrValue}</span>
                </p>
              );
            })}
          </div>
        </div>
        <div
          className={Style.prophoto}
          dangerouslySetInnerHTML={{ __html: bannnerdata.detailHtml }}
        ></div>
      </div>
      <div className={Style.footer}>
        <div className={Style.kefu}>
          <FaceRecognitionOutline fontSize={18} />
        </div>
        <div
          className={Style.goumai}
          onClick={() => {
            setVisible3(true);
          }}
        >
          立即购买
        </div>
        <div
          className={Style.addCar}
          onClick={() => {
            setVisible3(true);
          }}
        >
          加入购物车
        </div>
        <Popup
          visible={visible3}
          onMaskClick={() => {
            setVisible3(false);
          }}
          bodyStyle={{ height: "40vh" }}
        >
          {
            <div
              className={Style.carstyle}
              style={{
                height: "40vh",
                overflowY: "scroll",
                boxSizing: "border-box",
                padding: 15,
              }}
            >
              <div className={Style.header}>
                <img
                  src={colorcar
                    .filter((val) => val.id == colorid)
                    .map((val) => val.picUrl)}
                  style={{ width: 100 }}
                />
                <div className={Style.close}>
                  <p className={Style.cartejia}>{detaildata.promotionDesc}</p>
                  <p style={{ color: "red" }}>价格：{price?.basicPrice}</p>
                  <p>
                    已选择：
                    <strong>
                      {colorcar
                        .filter((val) => val.id == colorid)
                        .map((val) => val.value)}{" "}
                      {sizecar
                        .filter((val) => val.id == sizeid)
                        .map((val) => val.value)}
                    </strong>
                  </p>
                </div>
              </div>
              <div className={Style.color}>
                <p>颜色</p>
                <Selector
                  options={option1}
                  defaultValue={["1"]}
                  onChange={(arr, extend) => {
                    setcolorid(...arr);
                  }}
                  showCheckMark={false}
                />
              </div>
              <div className={Style.size}>
                <p>尺码</p>
                <Selector
                  options={option2}
                  defaultValue={["1"]}
                  onChange={(arr, extend) => {
                    console.log(...arr);
                    setsizeid(...arr);
                  }}
                  showCheckMark={false}
                />
              </div>
              <div className={Style.num} style={{ marginBottom: 10 }}>
                <p>数量</p>
                <Stepper
                  defaultValue={1}
                  onChange={(value: any) => {
                    console.log(value);
                    setnum(value)
                  }}
                  min={0}
                />
              </div>
              <div className={Style.carbtn}>
                <Button color="danger" >立即购买</Button>
                <Button
                  color="warning"
                  onClick={() => {
                    // 跳转购物车
                    // navigate("/shoppingCar");
                    dispatch(changeList(data))
                  }}
                >
                  加入购物车
                </Button>
              </div>
            </div>
          }
        </Popup>
      </div>
    </div>
  );
};

export default DetailView;
